import datetime
import threading

from typing import List

import psutil

from app.modle.models import CPU_Entity, CPU_Logical
from app.setting.config import MAX_HISTORY
from app.utils.util import get_current_time
class CpuMonitor:
    """CPU信息采集类"""
    def __init__(self):
        self.cpu_history = []
        self.time_history=[]
        self._lock = threading.Lock()
        self.last_cache = None  # 新增缓存属性

    async def get_cpu_info(self) -> CPU_Entity:
        """采集CPU整体信息（含逻辑核心详情）"""
        # 1. 物理核心 & 逻辑核心数
        physical_cores = psutil.cpu_count(logical=False) or 0
        logical_cores = psutil.cpu_count() or 0

        # 2. 系统负载
        load_avg = (0.0, 0.0, 0.0)
        if hasattr(psutil, "getloadavg"):
            try:
                load_avg = psutil.getloadavg()
            except NotImplementedError:
                load_avg = (0.0, 0.0, 0.0)

        # 3. 逻辑CPU数据：使用率、时间、频率
        cpu_percents = psutil.cpu_percent(percpu=True, interval=1)
        cpu_total_percent = psutil.cpu_percent(percpu=False, interval=1)
        cpu_times = psutil.cpu_times(percpu=True)  # 原始时间统计（秒）
        cpu_freqs = psutil.cpu_freq(percpu=True)  # 频率（MHz → GHz）

        with self._lock:
            self.cpu_history.append(cpu_total_percent)
            self.time_history.append(get_current_time())
            if len(self.cpu_history) > MAX_HISTORY:
                self.time_history.pop(0)
                self.cpu_history.pop(0)

        logical_cpus: List[CPU_Logical] = []
        for idx in range(logical_cores):
            # 防御性处理：避免索引越界
            if idx >= len(cpu_percents) or idx >= len(cpu_times):
                continue

            percent = cpu_percents[idx]
            times = cpu_times[idx]
            freq = cpu_freqs[idx%len(cpu_freqs)]

            logical_cpus.append(
                CPU_Logical(
                    cpu_logical_id=idx,
                    cpu_timestamp=datetime.datetime.now(),
                    cpu_percent=percent,
                    cpu_freq=(freq.current / 1000) if freq else 0.0,  # 转GHz
                    cpu_time_user=times.user,
                    cpu_time_system=times.system,
                    cpu_time_idle=times.idle,
                    cpu_time_IOWait=getattr(times, "iowait", 0.0),
                    cpu_time_irq=getattr(times, "irq", 0.0),
                    cpu_time_softIrq=getattr(times, "softirq", 0.0),
                    cpu_time_steal=getattr(times, "steal", 0.0),
                    cpu_time_guest=getattr(times, "guest", 0.0),
                    cpu_time_guest_nice=getattr(times, "guest_nice", 0.0),
                    cpu_time_nice=getattr(times, "nice", 0.0),
                    cpu_time_dpc=getattr(times, "dpc", 0.0),  # Windows专属
                )
            )


        # 4. 组装CPU整体模型
        cpu_entity = CPU_Entity(
            cpu_entity_id=0,
            cpu_totoal_percent = round(cpu_total_percent,2),
            cpu_count=physical_cores,
            cpu_loadavg_1m=load_avg[0] if len(load_avg) > 0 else 0.0,
            cpu_loadavg_5m=load_avg[1] if len(load_avg) > 1 else 0.0,
            cpu_loadavg_15m=load_avg[2] if len(load_avg) > 2 else 0.0,
            logicalCPUs=logical_cpus,
        )
        self.last_cache = cpu_entity  # 更新缓存
        return cpu_entity



    def get_cpu_total_percent(self) -> float:
        return psutil.cpu_percent(interval=1)


if __name__ == '__main__':
    cpu_percents = psutil.cpu_percent(percpu=True, interval=1)
    cpu_times = psutil.cpu_times(percpu=True)  # 原始时间统计（秒）
    cpu_freqs = psutil.cpu_freq(percpu=True)
    cpu_core = psutil.cpu_count()
    # print(cpu_freqs)
    # print(len(cpu_times))
    # print(len(cpu_percents))
    # print(cpu_core)
    cpumon = CpuMonitor()
    print(cpumon.get_cpu_entity().json())


